package com.xbn.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * @author XBN
 * @date 2020/10/15 16:47
 * @email 78742541@qq.com
 */

public class NIOClient {
    public static void main(String[] args) throws IOException {
       //得到一个网络通道
        SocketChannel socketChannel = SocketChannel.open();
        //设置非阻塞
        socketChannel.configureBlocking(false);
        //提供服务器端的ip和端口
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);
        //连接服务器
        if(!socketChannel.connect(inetSocketAddress))
        {
            //进入这个if语句，说明没有连接上
            while (!socketChannel.finishConnect())
            {
                System.out.println("连接期间不会阻塞，做其它工作....");
            }
        }
        //如果连接成功就发送数据
        String msg="hello";
        //直接将字符串转换为字节数组然后放到缓冲区中去，缓冲区的大小就等于字节数组的大小
        ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
        //发送数据，其实就是将buffer数据写入channel
        socketChannel.write(buffer);
        System.in.read();
    }
}
